layui.use(['layer', 'form', 'table', 'ztree', 'laydate', 'admin', 'ax'], function () {
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var $ZTree = layui.ztree;
    var $ax = layui.ax;
    var laydate = layui.laydate;
    var admin = layui.admin;


    var DT = {
        tableId: "userTable",    //表格id
        condition: {
            name: "",
            deptId: "",
        }
    };


    DT.initColumn = function () {
        return [[
            {type: 'numbers'},
            {field: 'userId', hide: true, sort: true, title: '用户id'},
            {field: 'account', sort: false, title: '登录账号'},
            {field: 'userName', sort: false, title: '姓名'},
            {field: 'deptName', sort: false, title: '部门'},
            // {field: 'createTime', sort: true, title: '创建时间'},
            //      {field: 'status',align: 'center', sort: false, templet: function(data){
            //             return data.status==1?'<span class="layui-badge layui-bg-green">启用</span>':'<span class="layui-badge layui-bg-orange">禁用</span>';
            //         }
            //         ,title: '状态'},
            {field: 'status', sort: true, templet: '#tableStateUser', title: '状态'},
            {align: 'center', toolbar: '#tableBar', title: '操作', minWidth: 260}
        ]];
    };

    // 修改用户状态
    form.on('switch(ckStateUser)', function (obj) {

        var userId = obj.elem.value;
        var status = obj.elem.checked ? 1 : 0;

        var ajax = new $ax(Sam.ctxPath + "/sam/user/status" , function () {
            Sam.success("操作成功!");
        }, function (data) {
            Sam.error( data.responseJSON.message );
            $(obj.elem).prop('checked', !obj.elem.checked);
            form.render('checkbox');
        });
        ajax.set("userId", userId);
        ajax.set("status", status);
        ajax.start();

    });


    DT.onClickDept = function (e, treeId, treeNode) {
        DT.condition.deptId = treeNode.id;
        DT.search();
    };


    DT.search = function () {
        var queryData = {};
        queryData['deptId'] = DT.condition.deptId;
        queryData['name'] = $("#name").val();
        table.reload(DT.tableId, {where: queryData});
    };


    DT.onEditUser = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '编辑用户',
            area: ['750px', '700px'],
            content: Sam.ctxPath + '/sam/user/edit/' + data.userId,
            end: function () {
                admin.getTempData('formOk') && DT.search();
            }
        });
    };

    DT.onDeleteUser = function (data) {
        var operation = function () {
            var ajax = new $ax(Sam.ctxPath + "/sam/user/delete/" + data.userId, function () {

                Sam.success("删除成功!");
                DT.search();
            }, function (data) {
                Sam.error("删除失败:" + data.responseJSON.message + "!");
            });
            ajax.start();
        };
        Sam.confirm("是否删除用户[" + data.userName + "]?", operation);
    };


    DT.openAddUser = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '新增用户',
            area: ['750px', '700px'],
            content: Sam.ctxPath + '/sam/user/add',
            end: function () {
                admin.getTempData('formOk') && DT.search();
            }
        });
    };

    DT.roleAssign = function (data) {
        layer.open({
            type: 2,
            title: '角色分配',
            area: ['650px', '500px'],
            content: Sam.ctxPath + '/sam/user/role_assign/' + data.userId,
            end: function () {
                DT.search();
            }
        });
    };

    /**
     * 重置密码
     *
     * @param data 点击按钮时候的行数据
     */
    DT.resetPassword = function (data) {
        Sam.confirm("您确定要重置该用户的密码吗?", function () {
            var ajax = new $ax(Sam.ctxPath + "/sam/user/reset", function (data) {

                Sam.success(data.message);
            }, function (data) {
                Sam.error("重置密码失败:" + data.responseJSON.message);
            });
            ajax.set("userId", data.userId);
            ajax.start();
        });
    };


    // 渲染表格
    var tableResult = table.render({
        elem: '#' + DT.tableId,
        url: Sam.ctxPath + '/sam/user/list',
        page: true,
        height: "full-98",
        cellMinWidth: 100,
        cols: DT.initColumn()
    });


    //初始化左侧部门树
    var ztree = new $ZTree("deptTree", "/sam/dept/tree");
    ztree.bindOnClick(DT.onClickDept);
    ztree.init();

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        DT.search();
    });

    // // 添加按钮点击事件
    $('#btnAdd').click(function () {
        DT.openAddUser();
    });

    // 工具条点击事件
    table.on('tool(' + DT.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            DT.onEditUser(data);
        } else if (layEvent === 'delete') {
            DT.onDeleteUser(data);
        } else if (layEvent === 'roleAssign') {
            DT.roleAssign(data);
        } else if (layEvent === 'reset') {
            DT.resetPassword(data);
        }
    });


});
